﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using ShareMarking.Entity;
using ShareMarking.Service;
using System.Net;
using System.IO;
using System.Net.Security;

namespace ShareMarking.Interface
{
    public class SDFC_Sync
    {
        protected string urlstr;
        protected string client_id ;
        protected string client_secret;
        protected string username;
        protected string password;
        protected string grant_type;

        public SDFC_Sync(string urlstr, string client_id, string client_secret, 
            string username, string password, string grant_type)
        {
            this.urlstr = urlstr;
            this.client_id = client_id;
            this.client_secret = client_secret;
            this.username = username;
            this.password = password;
            this.grant_type = grant_type;
        }

        public sfdc_urlresult GetUrl()
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("client_id", client_id);
            parameters.Add("client_secret", client_secret);
            parameters.Add("username", username);
            parameters.Add("password", password);
            parameters.Add("grant_type", grant_type);

            var postData = BuildQuery(parameters);
            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            ComLib.LogLib.Log4NetBase.Log("同步PNR数据,请求url:" + urlstr);
            ComLib.LogLib.Log4NetBase.Log("同步PNR数据,请求postData:" + postData);
            //byte[] data = Encoding.UTF8.GetBytes(postData);
            var result = click.Post(urlstr, postData);
            //var result = HttpPost2(urlstr, postData);
            ComLib.LogLib.Log4NetBase.Log("同步PNR数据,返回result:" + result);
            if (result == null && result == "")
             return null;
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Interface.sfdc_urlresult>(result);
            return resultentity;
        }

        private string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);

            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        public static string HttpPost2(string url, string paramData, Dictionary<string, string> headerDic = null)
        {
            string result = string.Empty;
            try
            {
                //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/x-www-form-urlencoded";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;//(SecurityProtocolType)3072;// 
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex) {
                ComLib.LogLib.Log4NetBase.Log("Eorrer:" + ex.Message+"/"+ex.StackTrace); 
            }
            //catch (WebException we)
            //{
            //    Stream responseStream =we.Response.GetResponseStream();
            //    using (StreamReader sread = new StreamReader(responseStream))
            //        {
            //            result = sread.ReadToEnd();
            //        }
            //    ComLib.LogLib.Log4NetBase.Log("Eorrer:" + result); 
            //    //ComLib.LogLib.Log4NetBase.Log("Eroor:" + we.ToString()+"/"+); 
            //}

            return result;
        }
        /// <summary>
        /// 获取医院和医院对应的PNR
        /// </summary>
        /// <returns></returns>
        public sfdc_hospresult GetHosptial()
        {
            var authen = GetUrl();

            var url = authen.instance_url + "/services/apexrest/getHospitalSync";
            var access = authen.access_token;
            //var url = "https://ap1.salesforce.com" + "/services/apexrest/getHospitalSync";
            //var access = "00D90000000ICD5!AQwAQMttJU4rKQx49xvHh7zEgjnMoZd2NSWgv_ZYQx26mExSpEJYV63God.7ZMZMNjioMr4QvNnd2MbaTEed1G1RDp_wXVyO";

            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;
            click.RequestHeaders.Add("Authorization", "Bearer " + access);
            var result = System.Text.Encoding.UTF8.GetString(click.GetData(url));
            //var result = "{\"hospitalLists\":[{\"attributes\":{\"type\":\"InfoToBeSynced__c\",\"url\":\"/services/data/v36.0/sobjects/InfoToBeSynced__c/a4Ap00000004Eg6EAE\"},\"Hospital_Region__c\":\"华西区\",\"Hospital_Area__c\":\"南宁区域\",\"DataType__c\":\"Hospital\",\"Hospital_MSR_StaffID__c\":\"5007786\",\"Hospital_Owner__c\":\"00590000000OSZtAAO\",\"Hospital_Code__c\":\"H121543\",\"Hospital_Name__c\":\"测试医院13\",\"Hospital_Active__c\":false,\"Sync_Status__c\":\"已上传\",\"Id\":\"a4Ap00000004Eg6EAE\",\"Sync_Date__c\":\"2016-02-22T08:57:11.066+0000\",\"Status__c\":\"上传成功\"},{\"attributes\":{\"type\":\"InfoToBeSynced__c\",\"url\":\"/services/data/v36.0/sobjects/InfoToBeSynced__c/a4Ap00000004EgaEAE\"},\"Hospital_Region__c\":\"华西区\",\"Hospital_Area__c\":\"南宁区域\",\"DataType__c\":\"Hospital\",\"Hospital_MSR_StaffID__c\":\"5007786\",\"Hospital_Owner__c\":\"00590000000OSZtAAO\",\"Hospital_Code__c\":\"H121544\",\"Hospital_Name__c\":\"测试医院15\",\"Hospital_Active__c\":false,\"Sync_Status__c\":\"已上传\",\"Id\":\"a4Ap00000004EgaEAE\",\"Sync_Date__c\":\"2016-02-22T08:57:11.066+0000\",\"Status__c\":\"上传成功\"}],\"hospitalInfo\":{\"attributes\":{\"type\":\"SyncInfo__c\"},\"IsSuccess__c\":true,\"IdString__c\":\"\",\"NameString__c\":\"\"},\"debugStr\":\"医院上传数据成功,上传数据:2件\"}";
            ComLib.LogLib.Log4NetBase.Log("1.=========得到医院列表,返回字符串：" + result);
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Interface.sfdc_hospresult>(result);

            return resultentity;
        }

        public sfdc_pnrresult GetPNR()
        {
            var authen = GetUrl();

            var url = authen.instance_url + "/services/apexrest/getUserSync";
            var access = authen.access_token;
            //var url = "https://ap1.salesforce.com" + "/services/apexrest/getUserSync";
            //var access = "00D90000000ICD5!AQwAQMttJU4rKQx49xvHh7zEgjnMoZd2NSWgv_ZYQx26mExSpEJYV63God.7ZMZMNjioMr4QvNnd2MbaTEed1G1RDp_wXVyO";

            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;
            click.RequestHeaders.Add("Authorization", "Bearer " + access);
            var result = System.Text.Encoding.UTF8.GetString(click.GetData(url));
            ComLib.LogLib.Log4NetBase.Log("同步PNR数据,返回字符串:" + result);
            //var result = "{\"PNRLists\":[{\"attributes\":{\"type\":\"InfoToBeSynced__c\",\"url\":\"/services/data/v36.0/sobjects/InfoToBeSynced__c/a4Ap00000004Eh9EAE\"},\"PNR_EmployeeNumber__c\":\"5004959.msr\",\"PNR_Region__c\":\"桂林\",\"PNR_Area__c\":\"南宁区域\",\"PNR_Name__c\":\"Chen Wei\",\"PNR_IsActive__c\":false,\"DataType__c\":\"PNR\",\"Sync_Status__c\":\"已上传\",\"Id\":\"a4Ap00000004Eh9EAE\",\"Sync_Date__c\":\"2016-02-23T09:39:54.007+0000\",\"Status__c\":\"上传成功\"},{\"attributes\":{\"type\":\"InfoToBeSynced__c\",\"url\":\"/services/data/v36.0/sobjects/InfoToBeSynced__c/a4Ap00000004EhEEAU\"},\"PNR_EmployeeNumber__c\":\"5004959.msr\",\"PNR_Region__c\":\"桂林\",\"PNR_Area__c\":\"南宁区域\",\"PNR_Name__c\":\"Chen Wei\",\"PNR_IsActive__c\":true,\"DataType__c\":\"PNR\",\"Sync_Status__c\":\"已上传\",\"Id\":\"a4Ap00000004EhEEAU\",\"Sync_Date__c\":\"2016-02-23T09:39:54.007+0000\",\"Status__c\":\"上传成功\"}],\"PNRInfo\":{\"attributes\":{\"type\":\"SyncInfo__c\"},\"IsSuccess__c\":true,\"IdString__c\":\"\",\"NameString__c\":\"\"},\"debugStr\":\"PNR上传数据成功,上传数据:2件\"}";
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Interface.sfdc_pnrresult>(result);

            return resultentity;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(value);
                    //postData.Append(HttpUtility.UrlEncode(name, Encoding.UTF8));
                    //postData.Append("=");
                    //postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
    }

    public class SFDC_QRCode
    {
        protected string httpstr;
        protected string signserect;

        public SFDC_QRCode(string httpstr, string signserect)
        {
            this.httpstr = httpstr;
            this.signserect = signserect;
        }

        public void Sync_HospQrCode()
        {
            //先得到所有的需要医院，并且不管新增修改都把关联IsNeedGet = true;
            var hplist = sfdc_HospitalService.Instance.Get_Entity_byWhere(sfdc_Hospital._.isneedupdate == true, null);
            ComLib.LogLib.Log4NetBase.Log("3-1、==========================得到医院更新的数据===========数量:" + hplist.Count);
            hplist.ForEach(o =>
            {
                #region 全部医院都生成二维码，不管是否激活，但是信息不同

                #region 是否有二维码
                var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                    qr_QrCodeRelate._.qr_Type == 2 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.Code__c);
                #endregion

                if (!has)
                {
                    #region 如果在关联表没有hsp对应的记录，就新增二维码
                        
                        #region 不查询弃用的二维码，直接使用新的
                        #region get sceneid
                        var sceneid = 0;
                        qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID ==2);//测试用999，正式改为2
                        sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                        #endregion

                        #region 编辑图文信息
                        List<extra> extra;

                        if (o.Active__c == true)
                        {
                            #region 编辑图文信息，激活医院
                            extra = new List<extra>(){ 
                            new extra { 
                                title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                shortdesc = "一键注册，终身礼遇", 
                                linkurl = string.Format("http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$NCCode={0}$PNRCode={1}$openId=####", o.Code__c,o.MSR_StaffID__c),
                                picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                            },
                            new extra{
                                title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                            },
                            new extra{
                                title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                shortdesc = "惊喜连连，准备好了么？", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                            }
                        };
                            #endregion
                        }
                        else
                        {
                            #region 编辑图文信息，未激活医院
                            extra = new List<extra>(){ 
                            new extra { 
                                title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                shortdesc = "一键注册，终身礼遇", 
                                linkurl = string.Format("http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$openId=####", o.Code__c,o.MSR_StaffID__c),
                                picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                            },
                            new extra{
                                title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                            },
                            new extra{
                                title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                shortdesc = "惊喜连连，准备好了么？", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                            }
                        };
                            #endregion
                        }
                        
                        var message = new message()
                        {
                            title = o.Name__c,
                            remark = o.Name__c + "的二维码",
                            sacode = "test",
                            scene_id = sceneid,
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                        var resultentity = vigo.CreateQrcode(message);
                        #endregion

                        while (resultentity.errcode == "12")
                        {
                            ComLib.LogLib.Log4NetBase.Log("二维码sceneid重复" + sceneid);
                            sceneid += 1;
                            message.scene_id = sceneid;
                            resultentity = vigo.CreateQrcode(message);
                        }

                        #region 将返回的信息保存
                        if (resultentity.errcode == "00")
                        {
                            #region 保存二维码
                            qr_QrCode qrcode = new qr_QrCode()
                            {
                                id = resultentity.message.id,
                                type = 2,
                                scene_id = resultentity.message.scene_id,
                                sacode = resultentity.message.sacode,
                                title = resultentity.message.title,
                                remark = resultentity.message.remark,
                                code_url = resultentity.message.code_url,
                                qrcode_url = resultentity.message.qrcode_url,
                                addtime = resultentity.message.addtime,
                                status = resultentity.message.status,
                                DateModified = DateTime.Now,
                                isdelete = false
                            };
                            qr_QrCodeService.Instance.Add_Entity(qrcode);
                            #endregion

                            #region 添加关联
                            qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                            {
                                qr_Type = 2,//2是医院
                                qr_CodeID = resultentity.message.id,
                                qr_Scene_ID = resultentity.message.scene_id,
                                rel_Code = o.Code__c,
                                IsDelete = false,
                                IsNeedGet=true,//是API需要请求的数据
                                CreateOn = DateTime.Now
                            };
                            qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                            #endregion

                            //更改二维码类型表
                            type.QT_CurrentIndex = sceneid;
                            type.QT_Used = type.QT_Used + 1;
                            type.QT_Surplus = type.QT_Surplus - 1;
                            qr_QrCodeTypeService.Instance.Update_Entity(type);
                        }
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("3、====新增医院二维码========新增===Hospital:" + o.Code__c + "::==sceneid==" + resultentity.message.scene_id);
                        #endregion
                        
                    #endregion
                }
                else
                {
                    #region 有二维码，更新二维码
                    #region 查询二维码
                    var relateforup = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                        qr_QrCodeRelate._.qr_Type == 2 && qr_QrCodeRelate._.IsDelete == false
                        && qr_QrCodeRelate._.rel_Code == o.Code__c);
                    var qrforup = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == relateforup.qr_Scene_ID);
                   
                    #endregion

                    #region 编辑图文信息
                    List<extra> extra ;

                    if (o.Active__c == true)
                    {
                        #region 激活的图文
                        extra = new List<extra>() { 
                            new extra { 
                                title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                shortdesc = "一键注册，终身礼遇", 
                                linkurl = string.Format("http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$NCCode={0}$PNRCode={1}$openId=####", o.Code__c,o.MSR_StaffID__c),
                                picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                            },
                            new extra{
                                title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                            },
                            new extra{
                                title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                shortdesc = "惊喜连连，准备好了么？", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                            }
                        };
                        #endregion
                    }
                    else
                    {
                        #region 编辑图文信息，未激活医院
                        extra = new List<extra>(){ 
                            new extra { 
                                title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                shortdesc = "一键注册，终身礼遇", 
                                linkurl = string.Format("http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$NCCode={0}$PNRCode={1}$openId=####", o.Code__c,o.MSR_StaffID__c),
                                picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                            },
                            new extra{
                                title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                            },
                            new extra{
                                title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                shortdesc = "惊喜连连，准备好了么？", 
                                linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                            }
                        };
                        #endregion
                    }
                    var message = new message2()
                    {
                        id = qrforup.id.ToString(),
                        title = o.Name__c,
                        remark = o.Name__c + "的二维码",
                        sacode = o.Name__c + "的二维码",
                        extra = extra
                    };
                    #endregion

                    #region 请求vigo 修改二维码
                    var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                    var result = vigo.UpdateQrcode(message);
                    #endregion

                    #region 将此医院置为需要API请求数据
                    relateforup.IsNeedGet = true;//是API需要请求的数据
                    relateforup.DateModified = DateTime.Now;
                    qr_QrCodeRelateService.Instance.Update_Entity(relateforup);
                    #endregion

                    ComLib.LogLib.Log4NetBase.Log("3、====更新医院二维码========更新===Hospital:" + o.Code__c);
                    #endregion
                }
                #endregion

                #region 将nc置为已修改
                o.isneedupdate = false;
                sfdc_HospitalService.Instance.Update_Entity(o);               
                #endregion
            });
            int hospcount = qr_QrCodeRelateService.Instance.Get_Entity_Record(qr_QrCodeRelate._.qr_Type == 2 && qr_QrCodeRelate._.IsNeedGet == true);
            ComLib.LogLib.Log4NetBase.Log("3-0、==========================关联表得到医院更新的数据===========数量:" + hospcount);
        }

        public void Sync_PNRQrCode()
        {
            //先得到所有的PNR并且不管新增修改都把关联IsNeedGet = true;
            var pnrlist = sfdc_PNRService.Instance.Get_Entity_byWhere(sfdc_PNR._.isneedupdate == true, null);
            ComLib.LogLib.Log4NetBase.Log("4-1、==========================得到PNR更新的数据===========数量:" + pnrlist.Count);
           
            pnrlist.ForEach(o =>
            {
                try
                {
                    if (o.IsActive__c == true)
                    {
                        #region 激活的PNR的处理
                        var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                            qr_QrCodeRelate._.qr_Type == 3 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.EmployeeNumber__c);

                        if (!has)
                        {
                            #region 如果在关联表没有NC对应的记录，就新增二维码
                            //查询是否有以前弃用的二维码
                            var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 3 &&
                                qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);
                            if (oldqr.IsNullOrCountLTE0())
                            {
                                #region get sceneid
                                var sceneid = 0;
                                qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID ==3);//999 测试
                                sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                                #endregion

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                    new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                                var message = new message()
                                {
                                    title = o.Name__c,
                                    remark = o.Name__c + "的二维码",
                                    sacode = "test",
                                    scene_id = sceneid,
                                    extra = extra
                                };
                                #endregion

                                #region 请求vigo 生成二维码
                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var resultentity = vigo.CreateQrcode(message);
                                #endregion

                                while (resultentity.errcode == "12")
                                {
                                    ComLib.LogLib.Log4NetBase.Log("二维码sceneid重复" + sceneid);
                                    sceneid += 1;
                                    message.scene_id = sceneid;
                                    resultentity = vigo.CreateQrcode(message);
                                }

                                #region 将返回的信息保存
                                if (resultentity.errcode == "00")
                                {
                                    #region 保存二维码
                                    qr_QrCode qrcode = new qr_QrCode()
                                    {
                                        id = resultentity.message.id,
                                        type = 3,
                                        scene_id = resultentity.message.scene_id,
                                        sacode = resultentity.message.sacode,
                                        title = resultentity.message.title,
                                        remark = resultentity.message.remark,
                                        code_url = resultentity.message.code_url,
                                        qrcode_url = resultentity.message.qrcode_url,
                                        addtime = resultentity.message.addtime,
                                        status = resultentity.message.status,
                                        DateModified = DateTime.Now,
                                        isdelete = false
                                    };
                                    qr_QrCodeService.Instance.Add_Entity(qrcode);
                                    #endregion

                                    #region 添加关联
                                    qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                    {
                                        qr_Type = 3,//3是PNR
                                        qr_CodeID = resultentity.message.id,
                                        qr_Scene_ID = resultentity.message.scene_id,
                                        rel_Code = o.EmployeeNumber__c,
                                        IsDelete = false,
                                        IsNeedGet = true,//是接口请求数据
                                        CreateOn = DateTime.Now,
                                        Chre_Source = "173",//20170612需求新增子来源、指定代码字段
                                        Appoint_Code = o.EmployeeNumber__c
                                    };
                                    qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                    #endregion

                                    //更改二维码类型表
                                    type.QT_CurrentIndex = sceneid;
                                    type.QT_Used = type.QT_Used + 1;
                                    type.QT_Surplus = type.QT_Surplus - 1;
                                    qr_QrCodeTypeService.Instance.Update_Entity(type);

                                    ComLib.LogLib.Log4NetBase.Log("3、====更新PNR二维码========新增===Hospital:" + o.EmployeeNumber__c + "::==sceneid==" + resultentity.message.scene_id);
                                }
                                #endregion
                            }
                            else
                            {
                                var qr = oldqr[0];

                                #region 更新二维码

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                    new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                                var message = new message2()
                                {
                                    id = qr.id.ToString(),
                                    title = o.Name__c,
                                    remark = o.Name__c + "的二维码",
                                    sacode = o.Name__c + "的二维码",
                                    extra = extra
                                };
                                #endregion

                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var result = vigo.UpdateQrcode(message);

                                #region 修改弃用的二维码状态为启用
                                qr.title = o.Name__c;
                                qr.remark = o.Name__c + "的二维码";
                                qr.isdelete = false;
                                qr.DateModified = DateTime.Now;
                                qr_QrCodeService.Instance.Update_Entity(qr);
                                #endregion

                                #endregion

                                #region 新建关联
                                qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                {
                                    qr_Type = 3,//3是PNR
                                    qr_CodeID = qr.id,
                                    qr_Scene_ID = qr.scene_id,
                                    rel_Code = o.EmployeeNumber__c,
                                    IsDelete = false,
                                    IsNeedGet = true,//是接口请求数据
                                    CreateOn = DateTime.Now,
                                    Chre_Source = "173",//20170612需求新增子来源、指定代码字段
                                    Appoint_Code = o.EmployeeNumber__c
                                };
                                qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                #endregion

                                ComLib.LogLib.Log4NetBase.Log("PNR为激活，使用旧的二维码：：：PNRCode：：" + o.EmployeeNumber__c + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                            }
                            #endregion
                        }
                        else
                        {
                            #region 也再更新一次
                            var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                                qr_QrCodeRelate._.qr_Type == 3 && qr_QrCodeRelate._.IsDelete == false
                                && qr_QrCodeRelate._.rel_Code == o.EmployeeNumber__c);

                            if (relate != null)
                            {
                                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                                if (qrcode != null)
                                {
                                    #region 更新二维码

                                    #region 编辑图文信息
                                    var extra = new List<extra>() { 
                                        new extra { 
                                            title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                            shortdesc = "一键注册，终身礼遇", 
                                            linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                        },
                                        new extra{
                                            title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                            shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                        },
                                        new extra{
                                            title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                            shortdesc = "惊喜连连，准备好了么？", 
                                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                        }
                                    };
                                    var message = new message2()
                                    {
                                        id = qrcode.id.ToString(),
                                        title = o.Name__c,
                                        remark = o.Name__c + "的二维码",
                                        sacode = o.Name__c + "的二维码",
                                        extra = extra
                                    };
                                    #endregion

                                    var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                    var result = vigo.UpdateQrcode(message);

                                    #region 将此PNR置为需要API请求数据
                                    relate.IsNeedGet = true;//是API需要请求的数据
                                    relate.Chre_Source = "173";//20170612需求新增子来源、指定代码字段
                                    relate.Appoint_Code = o.EmployeeNumber__c;
                                    relate.DateModified = DateTime.Now;
                                    qr_QrCodeRelateService.Instance.Update_Entity(relate);
                                    #endregion

                                    ComLib.LogLib.Log4NetBase.Log("PNR是激活的，再更新一次：：：PNRCode：：" + o.EmployeeNumber__c + "::==sceneid==::" + relate.qr_Scene_ID);
                                    #endregion
                                }
                            }

                            #endregion
                        }
                        #endregion
                    }
                    else //未激活
                    {
                        #region 未激活的PNR处理
                        var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                            qr_QrCodeRelate._.qr_Type == 3 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.EmployeeNumber__c);

                        if (relate != null)
                        {
                            var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                            if (qrcode != null)
                            {
                                #region 更新二维码，将二维码改成弃用

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                    new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                                var message = new message2()
                                {
                                    id = qrcode.id.ToString(),
                                    title = o.Name__c,
                                    remark = o.Name__c + "的旧二维码",
                                    sacode = o.Name__c + "的旧二维码",
                                    extra = extra
                                };
                                #endregion

                                #region 请求vigo 修改二维码
                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var result = vigo.UpdateQrcode(message);
                                #endregion

                                #region 修改的启用二维码状态为弃用
                                qrcode.isdelete = true;
                                qrcode.DateModified = DateTime.Now;
                                qr_QrCodeService.Instance.Update_Entity(qrcode);
                                #endregion

                                #endregion

                                #region 修改关联成删除
                                relate.IsDelete = true;
                                relate.IsNeedGet = true;//是接口请求数据
                                relate.Chre_Source = "173";//20170612需求新增子来源、指定代码字段
                                relate.Appoint_Code = o.EmployeeNumber__c;
                                relate.DateModified = DateTime.Now;
                                qr_QrCodeRelateService.Instance.Update_Entity(relate);
                                #endregion

                                ComLib.LogLib.Log4NetBase.Log("PNR未激活，将此二维码弃用：：：PNRCode：：" + o.EmployeeNumber__c + "::==sceneid==::" + relate.qr_Scene_ID);
                            }
                        }
                        else
                        {
                            ComLib.LogLib.Log4NetBase.Log("PNR未激活，没有此二维码：：：PNRCode：：" + o.EmployeeNumber__c);
                        }
                        #endregion
                    }

                    #region 将nc置为已修改
                    o.isneedupdate = false;
                    sfdc_PNRService.Instance.Update_Entity(o);
                    #endregion
                }
                catch (Exception ex)
                {
                    ComLib.LogLib.Log4NetBase.Log(ex.Message + ex.StackTrace);
                }
            });
           int pnrcount= qr_QrCodeRelateService.Instance.Get_Entity_Record(qr_QrCodeRelate._.qr_Type == 3 && qr_QrCodeRelate._.IsNeedGet == true);
           ComLib.LogLib.Log4NetBase.Log("4-0、==========================关联表得到PNR更新的数据===========数量:" + pnrcount);
        }

        /// <summary>
        /// 测试PNR更新指定代码方法
        /// </summary>
        public void Sync_PNRQrCode2()
        {
            //先得到所有的PNR并且不管新增修改都把关联IsNeedGet = true;

            var pnrlist = qr_QrCodeRelateService.Instance.Get_Entity_byWhere(qr_QrCodeRelate._.qr_Type == 1006 && qr_QrCodeRelate._.Chre_Source.IsNull(), null);
            
            ComLib.LogLib.Log4NetBase.Log("4-1、==========================得到PNR更新的数据===========数量:" + pnrlist.Count);

            pnrlist.ForEach(relate =>
            {
                try
                {
                    relate.Chre_Source = "";//20170612需求新增子来源、指定代码字段
                    relate.Appoint_Code = relate.rel_Code;
                    relate.DateModified = DateTime.Now;
                    qr_QrCodeRelateService.Instance.Update_Entity(relate);
                }
                catch (Exception ex)
                {
                    ComLib.LogLib.Log4NetBase.Log(ex.Message + ex.StackTrace);
                }
            });
            int pnrcount = qr_QrCodeRelateService.Instance.Get_Entity_Record(qr_QrCodeRelate._.qr_Type == 1006);
            ComLib.LogLib.Log4NetBase.Log("4-0、==========================关联表得到PNR更新的数据===========数量:" + pnrcount);
        }
    }
}
